package com.xingchi.tornado.security.model;

import lombok.Getter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 统一认证结果
 *
 * @author xingchi
 * @date 2025/9/4 22:13
 */
@Getter
public class UnifiedAuthenticationToken extends AbstractAuthenticationToken {

    private LoginData<? extends IUser> loginData;
    private String sessionId;

    public UnifiedAuthenticationToken() {
        super(new ArrayList<>());
    }

    public UnifiedAuthenticationToken(LoginData<? extends IUser> loginData) {
        super(Optional.ofNullable(loginData.getAuthorities()).orElse(new HashSet<>()).stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet()));
        this.loginData = loginData;
        this.sessionId = loginData.getSessionId();
        super.setAuthenticated(true);
    }


    @Override
    public Object getCredentials() {
        return loginData.getUser().getUserId();
    }

    @Override
    public Object getPrincipal() {
        return loginData.getUser();
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }

    @Override
    public String getName() {
        return loginData.getName();
    }

}
